const list = document.querySelector('.list');
let source;    // 保存自身元素

list.ondragstart = (e) => {
    source = e.target;
    setTimeout(() => {
        e.target.classList.add('moving');
    }, 0);
};

list.ondragenter = (e) => {
    const target = e.target;
    if (target === list || target === source) {
        return;
    }


    const sourceIndex = Array.from(list.children).indexOf(source);
    const targetIndex = Array.from(list.children).indexOf(target);

    if (sourceIndex < targetIndex) {
        list.insertBefore(source, target.nextSibling);
    } else {
        list.insertBefore(source, target);
    }

};

list.ondragend = (e) => {
    e.target.classList.remove('moving');
    source = null;
};

// 根据内容查找元素
function findElementByContent(content) {
    return Array.from(document.querySelectorAll('.listitem')).find(
        item => item.textContent.trim() === content
    );
}

// 封装的swap方法
function swap(contentA, contentB) {
    const elementA = findElementByContent(contentA);
    const elementB = findElementByContent(contentB);

    if (elementA === elementB) {
        return;
    }

    if (!elementA || !elementB) {
        console.error(`找不到内容为 ${contentA} 或 ${contentB} 的元素`);
        return Promise.reject();
    }

    return new Promise(resolve => {
        // 获取元素的当前位置
        const rectA = elementA.getBoundingClientRect();
        const rectB = elementB.getBoundingClientRect();

        // 计算移动距离
        const moveDownDistance = 40;
        const moveSidewaysDistance = rectB.left - rectA.left;

        // 创建克隆元素用于动画
        const cloneA = createAnimatedClone(elementA);
        const cloneB = createAnimatedClone(elementB);

        // 添加到容器
        const list = elementA.parentNode;
        list.appendChild(cloneA);
        list.appendChild(cloneB);

        // 隐藏原元素
        elementA.style.visibility = 'hidden';
        elementB.style.visibility = 'hidden';

        // 初始位置设置为原元素位置
        setElementPosition(cloneA, rectA);
        setElementPosition(cloneB, rectB);

        // 动画序列
        setTimeout(() => {
            cloneA.style.transform = `translateY(${moveDownDistance}px)`;
            cloneB.style.transform = `translateY(${moveDownDistance}px)`;

            setTimeout(() => {
                cloneA.style.transform = `translate(${moveSidewaysDistance}px, ${moveDownDistance}px)`;
                cloneB.style.transform = `translate(${-moveSidewaysDistance}px, ${moveDownDistance}px)`;

                setTimeout(() => {
                    cloneA.style.transform = `translate(${moveSidewaysDistance}px, 0)`;
                    cloneB.style.transform = `translate(${-moveSidewaysDistance}px, 0)`;

                    setTimeout(() => {
                        // 正确交换原元素位置（修复：确保中间元素不变）
                        const parent = elementA.parentNode;

                        // 获取两个元素在父容器中的位置
                        const indexA = Array.from(parent.children).indexOf(elementA);
                        const indexB = Array.from(parent.children).indexOf(elementB);

                        // 移除并重新插入元素以确保正确顺序
                        if (indexA < indexB) {
                            // 先移除B，再移除A，然后按正确顺序插入
                            parent.removeChild(elementB);
                            parent.removeChild(elementA);
                            parent.insertBefore(elementB, parent.children[indexA]);
                            parent.insertBefore(elementA, parent.children[indexB]);
                        } else {
                            // 先移除A，再移除B，然后按正确顺序插入
                            parent.removeChild(elementA);
                            parent.removeChild(elementB);
                            parent.insertBefore(elementA, parent.children[indexB]);
                            parent.insertBefore(elementB, parent.children[indexA]);
                        }

                        // 显示原元素
                        elementA.style.visibility = 'visible';
                        elementB.style.visibility = 'visible';

                        // 移除克隆元素
                        cloneA.remove();
                        cloneB.remove();

                        resolve();
                    }, 300);
                }, 300);
            }, 300);
        }, 0);
    });
}

// 创建用于动画的克隆元素
function createAnimatedClone(element) {
    const clone = element.cloneNode(true);
    clone.classList.add('moving-element');
    clone.style.position = 'absolute';
    clone.style.top = '0';
    clone.style.left = '0';
    clone.style.transition = 'transform 0.3s ease';
    clone.style.pointerEvents = 'none';
    return clone;
}

// 设置元素位置
function setElementPosition(element, rect) {
    const list = element.parentNode;
    element.style.left = `${rect.left - list.getBoundingClientRect().left}px`;
    element.style.top = `${rect.top - list.getBoundingClientRect().top}px`;
    element.style.width = `${rect.width}px`;
    element.style.height = `${rect.height}px`;
}

// 添加元素
document.getElementById('add-element').addEventListener('click', () => {
    const list = document.querySelector('.list');
    const items = list.querySelectorAll('.listitem');
    const count = items.length;

    if (count >= 10) {
        alert('元素数量不能超过10个');
        return;
    }

    const newItem = document.createElement('div');
    newItem.draggable = true;
    newItem.className = 'listitem';
    newItem.textContent = (count + 1).toString();

    list.appendChild(newItem);
});

// 删除元素
document.getElementById('remove-element').addEventListener('click', () => {
    const list = document.querySelector('.list');
    const items = list.querySelectorAll('.listitem');
    const count = items.length;

    if (count <= 5) {
        alert('元素数量不能少于5个');
        return;
    }

    list.removeChild(items[count - 1]);
});

// 打乱元素顺序
document.getElementById('shuffle-elements').addEventListener('click', async () => {
    const list = document.querySelector('.list');
    const items = Array.from(list.querySelectorAll('.listitem'));
    const count = items.length;

    // Fisher-Yates 洗牌算法
    for (let i = count - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        await swap(items[i].textContent, items[j].textContent);
    }
});

// 冒泡排序
document.getElementById('bubble-sort').addEventListener('click', async () => {
    const list = document.querySelector('.list');
    const items = Array.from(list.querySelectorAll('.listitem'));
    const n = items.length;

    for (let i = 0; i < n - 1; i++) {
        for (let j = 0; j < n - i - 1; j++) {
            const current = parseInt(items[j].textContent);
            const next = parseInt(items[j + 1].textContent);

            if (current > next) {
                await swap(items[j].textContent, items[j + 1].textContent);
                // 更新items数组引用
                items.splice(j, 2, items[j + 1], items[j]);
            }
        }
    }
});

// 选择排序
document.getElementById('selection-sort').addEventListener('click', async () => {
    const list = document.querySelector('.list');
    const items = Array.from(list.querySelectorAll('.listitem'));
    const n = items.length;

    for (let i = 0; i < n - 1; i++) {
        let minIndex = i;

        for (let j = i + 1; j < n; j++) {
            const current = parseInt(items[j].textContent);
            const min = parseInt(items[minIndex].textContent);

            if (current < min) {
                minIndex = j;
            }
        }

        if (minIndex !== i) {
            await swap(items[i].textContent, items[minIndex].textContent);
            // 更新items数组引用
            const temp = items[i];
            items[i] = items[minIndex];
            items[minIndex] = temp;
        }
    }
});